from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserModel
import jwt
from mymengduo.settings import SECRET_KEY

class LoginView(APIView):

    def post(self,request):


        # 获取传递来的用户名 密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 进行验证 是否正确是否存在
        user = UserModel.objects.filter(username=username,password=password).first()
        if user:
            info = {
                "uid":user.id,
                "username":user.username
            }
            # 验证通过 进行jwt令牌生成
            token = jwt.encode(info,SECRET_KEY)
            print(token)
            return Response({"msg": "登陆成功","token":token})
        # 返回
        else:
            # 验证失败
            return Response({"msg":"登陆失败"},status=401)

# 定义一个测试接口
class TestView(APIView):
    def get(self,request):
        # 解析这个令牌
        uid = request.COOKIES.get("uid")
        print(uid)
        if uid:
            return Response({"msg": "令牌有效"})
        else:

            return Response({"msg": "令牌无效"}, status=401)

    def post(self,request):
        uid = request.COOKIES.get("uid")
        # 解析这个令牌
        if uid:
            return Response({"msg": "令牌是有效"})
        else:
            return Response({"msg": "令牌无效"})

